package com.lin.service.MulThread;

import cn.hutool.core.util.ObjectUtil;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionCase {

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private Object object = null;
    private boolean produced = false; //是否已经生产
    private boolean consumed = false; //是否已经消费

    public void producer() {
        lock.lock();
        try {
            // 假设生产条件未满足 或 还未进行消费，等待
            while (!isProductionReady() || consumed) {
                condition.await();
            }
            // 进行生产操作
            object = new Object();
            produced = true;
            System.out.println("生产完成,可以消费");
            // 通知消费者可以消费
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void consumer() {
        lock.lock();
        try {
            // 假设消费条件未满足，等待
            while (!isConsumptionReady() ||!produced) {
                condition.await();
            }
            // 进行消费操作
            object = null;
            consumed = true;
            System.out.println("消费完成");
            // 通知生产者可以生产
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private boolean isProductionReady() {
        // 这里可以根据实际情况判断生产条件是否满足
        return true;
    }

    private boolean isConsumptionReady() {
        // 这里可以根据实际情况判断消费条件是否满足
        return true;
    }

    public static void main(String[] args) {
        ConditionCase conditionCase = new ConditionCase();

        new Thread(() -> conditionCase.consumer()).start();
        new Thread(() -> conditionCase.producer()).start();
    }
}
